//
//  MessageListViewController.swift
//  ezyform
//
//  Created by Hubert on 2022/5/7.
//  Copyright © 2022 Client.Solution Pty Ltd. All rights reserved.
//

import UIKit
import MJRefresh
import HandyJSON
import SwiftyJSON
import Alamofire

class MessageListViewController: BaseViewController {
    private var dataArray: [NotificationModel] = []
    private var currentPage: String = "1"
    private var nextPage: String = ""
    let customView = MessageListView()
    override func viewDidLoad() {
        super.viewDidLoad()
        self.initUI()
        
        NotificationCenter.default.addObserver(self, selector: #selector(messageListRefreshNotification(_:)), name: NSNotification.Name(rawValue: "messageListRefreshNotification"), object: nil)
    }
    func initUI(){
        self.view = self.customView
        self.customView.setTitleInfo("Notification")
        
        self.customView.tableView.dataSource = self
        self.customView.tableView.delegate = self
        self.customView.tableView.mj_header = MJRefreshNormalHeader(refreshingTarget: self, refreshingAction: #selector(headerLoad(_:)))
        self.customView.tableView.mj_footer = MJRefreshBackNormalFooter(refreshingTarget: self, refreshingAction: #selector(footerLoad(_:)))
        self.customView.searchTextfield.addTarget(self, action: #selector(searchClick), for: UIControl.Event.editingDidBegin)
        self.customView.allReadBtn.addTarget(self, action: #selector(allReadBtnClick), for: .touchUpInside)
        self.loadData(true)
    }
    @objc func headerLoad(_ header: MJRefreshNormalHeader){
        self.currentPage = "1"
        dataArray.removeAll()
        self.loadData( header: header)
    }
    
    @objc func footerLoad(_ footer: MJRefreshBackNormalFooter){
        self.currentPage = self.nextPage
        self.loadData(footer: footer)
    }
    func loadData(_ loadingFlag: Bool = false,header: MJRefreshNormalHeader? = nil, footer: MJRefreshBackNormalFooter? = nil){
        //
        if loadingFlag {
            ModelViewUtil.shared.showLoadingView()
        }
        let vm = NotificationService()
        
        vm.setBlockAfterNetwork{ [weak self]result, otherInfo in
            ModelViewUtil.shared.hideLoadingView()
            guard let strongSelf = self else { return }

            if let tempHeader = strongSelf.customView.tableView.mj_header {
                tempHeader.endRefreshing()
            }
            if let tempFooter = strongSelf.customView.tableView.mj_footer {
                tempFooter.endRefreshing()
            }
            if let pageInfo = otherInfo {
                strongSelf.nextPage = pageInfo.object(forKey: "X-Next-Page") as? String ?? ""
            }
            
            if let _ = strongSelf.customView.tableView.mj_footer ,strongSelf.nextPage != "" {
                strongSelf.customView.tableView.mj_footer?.resetNoMoreData()
            }else{
                strongSelf.customView.tableView.mj_footer?.endRefreshingWithNoMoreData()
            }

            let json = JSON(result!)
            if let list = JSONDeserializer<NotificationModel>.deserializeModelArrayFrom(json: json.rawString()) as? Array<NotificationModel>{
                if strongSelf.currentPage == "1"{
                    strongSelf.dataArray = list
                }else{
                    strongSelf.dataArray += list
                }

                strongSelf.customView.tableView.reloadData()
            }
            //没有数据显示not data view，有数据隐藏not data view
            strongSelf.customView.tableView.showResultView(nodataFlag: strongSelf.dataArray.count == 0 ? true: false)
            
        } errorBlock: { code, error in
            //加载完再endrefreshing,解决上拉加载时tableview抖动死循环请求网络无限次加载的问题
            if let tempHeader = header {
                tempHeader.endRefreshing()
            }
            if let tempFooter = footer {
                tempFooter.endRefreshing()
            }
            ModelViewUtil.shared.hideLoadingView()
            Tool().showErrorInfo(code, error)
        }
        vm.getNotificationList(self.currentPage)
    }

    // MAKR: - messagePushNotification
    @objc func messageListRefreshNotification(_ notification: NSNotification){
        self.currentPage = "1"
        self.loadData()
    }
    // MAKR: = searchClick
    @objc func searchClick() {
        let vc = MessageSearchViewController()
        let nav = BaseNavigationController.init(rootViewController: vc)
        nav.modalPresentationStyle = .fullScreen
        self.present(nav, animated: false)
    }
    
    @objc func allReadBtnClick() {
        if APPConfig.loginInfo.unReadNotificationCount == 0 { // 判断是否都已读
            return
        }
        let service = NotificationService()
        service.setBlockAfterNetwork {[weak self] (result, _) in
            ModelViewUtil.shared.hideLoadingView()
            guard let self = self else { return }
            for (_, model) in self.dataArray.enumerated() {
                model.is_read = true
            }
            self.customView.tableView.reloadData()
            var alertMsg = ""
            if APPConfig.loginInfo.unReadNotificationCount == 1 {
                alertMsg = "1 notification marked as read."
            }else{
                alertMsg = "\(APPConfig.loginInfo.unReadNotificationCount) notifications marked as read."
            }
            //清空unread 的数量
            APPConfig.loginInfo.unReadNotificationCount = 0
            Tool().showAlertViewWithOneBtn(message: alertMsg)
        } errorBlock: { (code, error) in
            ModelViewUtil.shared.hideLoadingView()
            Tool().showErrorInfo(code, error)
        }
        ModelViewUtil.shared.showLoadingView()
        service.setNotificationReadStatus()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.setNavigationBarHidden(true, animated: false)
        //set background color of navigation bar
        self.tabBarController?.tabBar.isHidden = true
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        DebugLog("\(self) didReceiveMemoryWarning")
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
}

extension MessageListViewController: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        var cell : MessageTableViewCell? = tableView.dequeueReusableCell(withIdentifier: MessageTableViewCell.reuseCellIdentifier) as? MessageTableViewCell
        if (cell == nil){
            cell = MessageTableViewCell(style: .default, reuseIdentifier: MessageTableViewCell.reuseCellIdentifier)
        }
        if self.dataArray.count > indexPath.row{
            cell?.setData(self.dataArray[indexPath.row])
        }
        return cell!
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.dataArray.count
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let model = self.dataArray[indexPath.row]
        let vc = MessageDetailViewController()
        vc.refreshListBlock = { [weak self] in //设置成已读状态
            guard let strongSelf = self else { return }
            if strongSelf.dataArray.count > indexPath.row{
                if let indexRow = strongSelf.dataArray.firstIndex(where: { $0.id == model.id}) {
                    strongSelf.dataArray[indexRow].is_read = true
                    strongSelf.customView.tableView.reloadRows(at: [IndexPath(row: indexRow, section: 0)], with: UITableView.RowAnimation.none)
                }
            }
        }
        vc.id = model.id
        vc.hidesBottomBarWhenPushed = true
        self.navigationController?.pushViewController(vc, animated: false)
    }
}
